import 'package:aero_frisbee/app/model/af_short_link_model/af_short_link_model.dart';
import 'package:aero_frisbee/app/model/cache_bind_video_model/cache_bind_video_model.dart';
import 'package:aero_frisbee/app/state/af_app_state_ext.dart';
import 'package:aero_frisbee/core/extension/string_ext.dart';
import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:aero_frisbee/pages/entry/app_tab_page.dart';
import 'package:aero_frisbee/pages/modues/message/pages/followed/view_model/af_followed_list_view_model.dart';
import 'package:aero_frisbee/pages/modues/message/pages/message/message_detail/viwe_model/af_message_detail_view_model.dart';
import 'package:aero_frisbee/pages/modues/post/af_profile_detail_screen/views/af_more_action_sheet.dart';
import 'package:aero_frisbee/pages/modues/post/af_profile_detail_screen/views/af_report_options_sheet.dart';
import 'package:aero_frisbee/pages/modues/videos/view_model/af_video_view_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:video_player/video_player.dart';
import 'package:visibility_detector/visibility_detector.dart';

import 'post_gift_sheet_view.dart';
import 'video_container.dart';

class AfVideoCell extends ConsumerStatefulWidget {
  const AfVideoCell({super.key, required this.item});
  final AfShortLinkModel item;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _AfVideoCellState();
}

class _AfVideoCellState extends ConsumerState<AfVideoCell> {
  late VideoPlayerController _controller;
  @override
  Widget build(BuildContext context) {
    ref.listen(tabIndexProvider, (previousData, newData) {
      if (newData != previousData) {
        _controller.pause();
        setState(() {});
      }
    });
    final userInfo = ref
        .watch(getUserInfoFutureProvider(
            userId: widget.item.cacheBind?.homeUser?.userId ?? ''))
        .maybeWhen(
          orElse: () => null,
          data: (data) => data,
        );

    ref.listen(blockServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        Future.delayed(const Duration(milliseconds: 500), () {
          setState(() {
            _replay();
          });
        });

        ///需要重新刷新下界面
      }
    });
    ref.listen(reportServiceProvider, (previousData, newData) {
      newData.showError();
      newData.showLoadding();
      final isOk =
          newData.maybeWhen(ready: ((data) => data), orElse: () => false);
      if (isOk) {
        "Report Success".toast(
          onDismiss: () {
            Future.delayed(const Duration(milliseconds: 500), () {
              setState(() {});
            });
          },
        );
      }
    });
    final curShortLinkItem = ref.watch(curShortLinkProvider(item: widget.item));
    return Stack(
      children: <Widget>[
        Container(
          alignment: Alignment.center,
          child: Center(
            child: _controller.value.isInitialized
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          _controller.value.isPlaying
                              ? _controller.pause()
                              : _controller.play();
                          setState(() {});
                        },
                        child: Stack(children: [
                          VisibilityDetector(
                            key: const Key('my-widget-key'),
                            onVisibilityChanged: (info) {
                              if (info.visibleFraction == 0) {
                                _controller.pause();
                                setState(() {});
                              }
                            },
                            child: VideoContainer.fromController(_controller),
                          ),
                          Positioned.fill(
                            child: Visibility(
                              visible: !_controller.value.isPlaying,
                              child: Center(
                                child: Assets.icons.iconVideoPlayBtn
                                    .image(width: 79),
                              ),
                            ),
                          )
                        ]),
                      ),
                    ],
                  )
                : const Center(child: CircularProgressIndicator()),
          ),
        ),
        Positioned(
          bottom: 0,
          top: 0,
          right: 20,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              const SizedBox(
                height: 20,
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  showAfMoreActionSheet(
                    context,
                    isFriend: userInfo?.isFriend == true,
                    isBlock: userInfo?.isBlock == true,
                    onFollowClick: () {
                      if (userInfo?.isFriend == true) {
                        ref
                            .read(unfriendServiceProvider.notifier)
                            .unfriend(userId: userInfo?.userId ?? '');
                      } else {
                        ref
                            .read(addFriendServiceProvider.notifier)
                            .addFriend(userId: userInfo?.userId ?? '');
                      }
                    },
                    onBlackClick: () {
                      if (userInfo?.isBlock == true) {
                        ref
                            .read(unblockServiceProvider.notifier)
                            .unblock(broadcasterId: userInfo?.userId ?? '');
                      } else {
                        ref
                            .read(blockServiceProvider.notifier)
                            .block(broadcasterId: userInfo?.userId ?? '');
                      }
                    },
                    onReportClick: () {
                      showAfReportOptionsSheet(
                        context,
                        onReportClick: (report) {
                          ref.read(reportServiceProvider.notifier).report(
                              complainSub: report,
                              userId: userInfo?.userId ?? '');
                        },
                      );
                    },
                  );
                },
                child: Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: Assets.icons.iconMore.image(width: 35),
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  ref
                      .read(afVideoListServiceProvider.notifier)
                      .toggleLike(shortLinkeItem: widget.item);
                },
                child: Padding(
                  padding: const EdgeInsets.all(4.0),
                  child: curShortLinkItem.isLike
                      ? Assets.icons.videoLikeLight.image(width: 35)
                      : Assets.icons.videoLikeNormal.image(width: 35),
                ),
              ),
              const SizedBox(
                height: 160,
              ),
              SizedBox(
                height: MediaQuery.of(context).padding.bottom,
              ),
            ],
          ),
        ),
        Positioned(
          right: 0,
          left: 0,
          bottom: 0,
          child: Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  color: const Color(0xff333333).withOpacity(0.3),
                ),
                margin: const EdgeInsets.only(top: 10),
                child: Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 12, vertical: 20),
                      child: Row(
                        children: [
                          Padding(
                            padding: const EdgeInsets.only(right: 12),
                            child: Stack(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.all(5.0),
                                  child: CircleAvatar(
                                    radius: 22,
                                    backgroundImage: NetworkImage(
                                      widget.item.cacheBind?.homeUser?.avatar ??
                                          '',
                                    ),
                                  ),
                                ),
                                Positioned(
                                  bottom: 0,
                                  right: 0,
                                  child: Visibility(
                                    visible: userInfo?.isFriend != true,
                                    child: GestureDetector(
                                      behavior: HitTestBehavior.opaque,
                                      onTap: () {
                                        ref
                                            .read(addFriendServiceProvider
                                                .notifier)
                                            .addFriend(
                                                userId: userInfo?.userId ?? '');
                                      },
                                      child: Container(
                                        decoration: const BoxDecoration(),
                                        child: Padding(
                                          padding: const EdgeInsets.symmetric(
                                            horizontal: 2,
                                            vertical: 2,
                                          ),
                                          child: Assets
                                              .icons.iconProfileFollowBtn
                                              .image(width: 22),
                                        ),
                                      ),
                                    ),
                                  ),
                                )
                              ],
                            ),
                          ),
                          Expanded(
                            child: Column(
                              children: [
                                Row(
                                  children: [
                                    Flexible(
                                      child: Text(
                                        widget.item.cacheBind?.homeUser
                                                ?.nickname ??
                                            '',
                                        style: const TextStyle(
                                          color: Color(0xffffffff),
                                          fontWeight: FontWeight.normal,
                                          fontSize: 15,
                                        ),
                                        textAlign: TextAlign.left,
                                        overflow: TextOverflow.ellipsis,
                                        maxLines: 1,
                                      ),
                                    ),
                                    Padding(
                                      padding: const EdgeInsets.all(8.0),
                                      child: widget.item.cacheBind!.markImg,
                                    ),
                                  ],
                                ),
                                const SizedBox(
                                  height: 6,
                                ),
                                Align(
                                  alignment: Alignment.topLeft,
                                  child: Text(
                                    widget.item.title ?? '',
                                    style: const TextStyle(
                                      color: Color(0xffffffff),
                                      fontWeight: FontWeight.normal,
                                      fontSize: 11,
                                    ),
                                    textAlign: TextAlign.left,
                                    overflow: TextOverflow.ellipsis,
                                    maxLines: 2,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: MediaQuery.of(context).padding.bottom,
                    )
                  ],
                ),
              ),
              Positioned(
                top: 0,
                right: 20,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    final homeUser = widget.item.cacheBind?.homeUser;
                    if (homeUser != null) {
                      showPostGiftSheetView(context, homeUser: homeUser);
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(4.0),
                    child: Assets.icons.iconGfitBtn.image(width: 35),
                  ),
                ),
              )
            ],
          ),
        ),
      ],
    );
  }

  @override
  void initState() {
    _controller =
        VideoPlayerController.networkUrl(Uri.parse(widget.item.mediaUrl ?? ''))
          ..initialize().then((_) {
            // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
            _controller.setLooping(true);
            _controller.play();
            setState(() {});
          });
    super.initState();
  }

  _replay() {
    _controller.pause();
    _controller =
        VideoPlayerController.networkUrl(Uri.parse(widget.item.mediaUrl ?? ''))
          ..initialize().then((_) {
            // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
            // _controller.setLooping(true);
            _controller.play();
            setState(() {});
          });
  }

  @override
  void dispose() {
    _controller.pause();
    _controller.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(AfVideoCell oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}

class AFVideoPlayerView extends StatelessWidget {
  const AFVideoPlayerView({Key? key, required this.controller})
      : super(key: key);
  final VideoPlayerController controller;

  @override
  Widget build(BuildContext context) {
    return VideoPlayer(controller);
  }
}
